<?php
namespace app\mobile\controller;
use app\common\controller\Base;
use think\Db;
use app\index\model\Username;
use app\common\model\StateChange;
use think\Cookie;

class User extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        //用户中心所需参数
        $start = array(
                'user_all'                     =>$this->user_all,
                'logo'                          =>$this->logo,
                'app_down'                =>$this->app_down,
                'now_time_windows' => $this->now_time_windows,
                'usnameclass'            => $this->usnameclass
        );
        
        $this->state = new StateChange();
        $this->assign($start);
    }

    /**手机端登录页面【展示】**/
    public function login()
    {
        if($this->user_all['id'] > 0)  //登录情况下,直接跳转到首页
        {
            $this->redirect('index/mhome');
        }
        $title = '登录';
        $this->assign('title',$title);
        //获取一张图片
        $login_bj = Db::name('sjgg')->where('gg_class>=5')->find();
        $this->assign('login_bj',$login_bj);
        $this->assign('title','登录');
        return $this->fetch();
    }
	public function agreement(){
		return $this->fetch();
	}
    
    /** 手机端注册 **/
    public function register()
    {
        //获取验证码开关
        $codeif = Db::name('xt_reg')->find();
        //获取一张图片
        $login_bj = Db::name('sjgg')->where('gg_class>=5')->find();
        $this->assign('code_open',$codeif['codo_open']);
        $this->assign('tjm_open',$codeif['tjr_open']);
        $this->assign('tjm',cookie('vip'));
        $this->assign('login_bj',$login_bj);
        $this->assign('title','注册');
        return $this->fetch();
    }


    /**
     * @Author
     * @Purpose 注册验证
     * @Time 2018-03-08
     */
    public function regVerify()
    {
        $user_model = new Username();
        $reg_user = input('post.reg_user') ? input('post.reg_user') : '';
        $reg_pass = input('post.reg_pass') ? input('post.reg_pass') : '';
        $phone = input('post.reg_phone') ? input('post.reg_phone') : '';
        $reg_recommend = input('post.reg_recommend') ? input('post.reg_recommend') : '';
        $verify_code = input('post.verify_code') ? input('post.verify_code') : '';

        if($reg_user && $reg_pass) {
            $reg_user = strtolower($reg_user);
            //验证用户名密码
            if(!checkNameInfo($reg_user)) {
                echo 3;exit;
            }
            if(!checkPassInfo($reg_pass)) {
                echo 4;exit;
            }
            
            //判断是否需要验证验证码
            $codeif = Db::name('xt_reg')->find();
            if($codeif['codo_open'] == 1) {
                if(!$verify_code) {
                    echo 6;exit;
                }
                if(!captcha_check($verify_code)) {
                    echo 6;exit;
                }
            }
            
            //验证用户手机号
            if($phone && !checkPhone($phone)) {
                echo 7;exit;
            }
            $agent = '';
            $arr = array('id'=>0,'username'=>'','recommend'=>['0'=>'','1'=>0]);
            //判断推荐码是否有效
            $tjm_open = $codeif['tjr_open'];
            if ($reg_recommend) {
                $dl = Db::name('username')->field('username,tjm,id')->where(['tjm' => ['<>', '']])->select();
                foreach ($dl as $val) {
                    if (strpos($val['tjm'], $reg_recommend) !== false) {
                        $arr['username'] = $val['username'];
                        $arr['id'] = $val['id'];
                        $val['tjm'] = explode('|', $val['tjm']);

                        foreach ($val['tjm'] as $value) {
                            if (strpos($value, $reg_recommend) !== false) {
                                if (strpos($value, '-') !== false) {
                                    $arr['recommend'] = explode('-', $value);
                                } else {
                                    $arr['recommend'][0] = $value;
                                    $arr['recommend'][1] = 0;
                                }
                            }
                        }
                    }
                }
                if ($arr['recommend'][0] != $reg_recommend) {
                    echo 8;
                    exit;
                }
            }elseif(1==intval( $tjm_open )){
                echo 9;
                exit;
            }
            //解析IP
            $position = '';
           // $ip = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip={$this->login_ip}");
           // $ip = @file_get_contents("http://tool.chinaz.com/ipwhois?q={$this->login_ip}");
           /* if($ip > 0) {
                $ip = json_decode($ip,true);
                if($ip['province'] && $ip['city']) {
                    $position = $ip['province'].' '.$ip['city'];
                } else {
                    $position = $ip['country'];
                }
            }*/
            //注册防骚扰
            $ruzhuc = Db::name('xt_zcfsr')->find();
            if($ruzhuc['open'] == 1) {
                $ntimess = strtotime(date('Y-m-d').' 00:00:00');
                $zcount = Db::name('username')->where("reg_ip='{$this->login_ip}' AND reg_time>'{$ntimess}' ")->count();
                if($zcount >= $ruzhuc['one_day_count']) {
                    echo 2;exit;
                }
            }
            //验证是否用户名已注册
            $usercf = Db::name('username')->where('username',$reg_user)->find();
            if($usercf['id'] > 0) {
                echo 5;exit;
            }
            //是否开启注册送金额
            $t = Db::name('xt_caijin')->where('id',1)->find();
            if($t['open'] == 1) {
                $je = $t['je'];
                $dml = $t['cj_dml'];
            } else {
                $je = 0;
                $dml = 0;
            }
            //将用户信息插入表
            $reg_pass = md5($reg_pass);
            $ntime = time();
            $login_key = suiji_zifu(15);

            $user_model->setNewUser($arr['id'],$dml,$reg_user,$reg_pass,$arr['username'],$je,$ntime,$this->login_ip,$position,1,'',0,2,$login_key);
            $data['mobile']=$phone;
            $data['zcjje'] = $je;
            $data['reg_je'] = $je;

            if($arr['recommend'][1]>0){
            	$data['dl']=1;
                $data['dl_time'] = time();
            	$data['tjm']=$this->code();
            	$data['fandian']=$arr['recommend'][1];
            }
            Db::name('username')->where('username',$reg_user)->update($data);
            if($je>0){
            	$this->state->UserFaSong($reg_user, "您注册账号赠送：".$je."元.已到账，请注意查收！");
                $data = array(
                    'username'=>$reg_user,
                    'user_class'=>1,
                    'cjje'=>$je,
                    'fstime'=>time(),
                    'beizhu' => '系统赠送，手机H5用户注册，赠送彩金',
                    'czadmin' => '系统赠送',
                    'cjhje'=>$je,
                );
                Db::name('caijin_list')->insert($data);
            }
            Db::name('username')->where('username',$reg_user)->setInc('login_num');
            //标记用户为登录状态
            cookie("username",$reg_user);
            cookie("password",$reg_pass);
            cookie("login_key",$login_key);
            Cookie::delete('vip');

            echo 'ok';
        } else {
           echo 1;exit;
        }
        
    }
    public function changeHeader(){
        $img = isset($_POST['img'])? $_POST['img'] : '';
        // 获取图片
        list($type, $data) = explode(',', $img);
        // 判断类型
        $ext = '';
        if(strstr($type,'image/jpeg')!=''){
            $ext = '.jpg';
        }elseif(strstr($type,'image/gif')!=''){
            $ext = '.gif';
        }elseif(strstr($type,'image/png')!=''){
            $ext = '.png';
        }
        $base_path = ROOT_PATH.'public'.DS.'uploads'.DS.'avatar'.DS; //存放目录
        if(!is_dir($base_path)){
            @mkdir($base_path,0777,true);
        }
        // 生成的文件名
        $photo = time().$ext;
        $orgImg = Db::name('username')->where(['username'=>$this->user_all['username']])->value("img");
        if( @file_put_contents($base_path.$photo, base64_decode($data), true) && Db::name('username')->where(['username'=>$this->user_all['username']])->update(['img'=>basename( $photo )]) ){
            if( !empty($orgImg)) @unlink($base_path.$orgImg);
            return 1;
        }
        return 0;
    }
    function code(){
    	$code=rand('00000000','99999999');
    	
    	if($code != ''){
    		$yzm = Db::name('username')->field('tjm')->select();
    		$tjm = '';
    		foreach ($yzm as $v){$tjm .= $v['tjm'].'--';}
    		if(strstr($tjm, $code)!==false){
    			$this->code();
    		}
    	}
    	return $code;
    }
    public function expand(){
        $info = Db::name('agent_url')->find();
        $this->assign('tjm',input('vip',''));
        $this->assign('title','注册');
        $this->assign('info',$info);
        return $this->fetch();
    }
    public function expandVerify()
    {
        $user_model = new Username();
        $reg_user = input('post.reg_user') ? input('post.reg_user') : '';
        $reg_pass = input('post.reg_pass') ? input('post.reg_pass') : '';
        $phone = input('post.reg_phone') ? input('post.reg_phone') : '';
        $reg_recommend = input('post.reg_recommend') ? input('post.reg_recommend') : '';

        if($reg_user && $reg_pass) {
            $reg_user = strtolower($reg_user);
            //验证用户名密码
            if(!checkNameInfo($reg_user)) {
                echo 3;exit;
            }
            if(!checkPassInfo($reg_pass)) {
                echo 4;exit;
            }

            //验证用户手机号
            if($phone && !checkPhone($phone)) {
                echo 7;exit;
            }
            $arr = array('id'=>0,'username'=>'','recommend'=>['0'=>'','1'=>0]);
            //判断推荐码是否有效
            if ($reg_recommend) {
                $dl = Db::name('username')->field('username,tjm,id')->where('swzh',0)->select();

                foreach ($dl as $val) {
                    /*if (strpos($val['tjm'], $reg_recommend) !== false) {
                        $arr['username'] = $val['username'];
                        $arr['id'] = $val['id'];
                        $val['tjm'] = explode('|', $val['tjm']);

                        foreach ($val['tjm'] as $value) {
                            if (strpos($value, $reg_recommend) !== false) {
                                if (strpos($value, '-') !== false) {
                                    $arr['recommend'] = explode('-', $value);
                                } else {
                                    $arr['recommend'][0] = $value;
                                    $arr['recommend'][1] = 0;
                                }
                            }
                        }
                    }*/
                    if($val['tjm']==$reg_recommend){
                        $data['dl']=1;
                        $data['dl_time'] = time();
                        $data['tjm']=$this->code();
                        $arr['recommend'][0]=$val['tjm'];
                        $arr['username'] = $val['username'];
                        $arr['id']=$val['id'];
                    }
                }
                if ($arr['recommend'][0] != $reg_recommend) {
                    echo 8;
                    exit;
                }
            }
            //解析IP
            $position = '';
            //注册防骚扰
            $ruzhuc = Db::name('xt_zcfsr')->find();
            if($ruzhuc['open'] == 1) {
                $ntimess = strtotime(date('Y-m-d').' 00:00:00');
                $zcount = Db::name('username')->where("reg_ip='{$this->login_ip}' AND reg_time>'{$ntimess}' ")->count();
                if($zcount >= $ruzhuc['one_day_count']) {
                    echo 2;exit;
                }
            }
            //验证是否用户名已注册
            $usercf = Db::name('username')->where('username',$reg_user)->find();
            if($usercf['id'] > 0) {
                echo 5;exit;
            }
            //是否开启注册送金额
            $t = Db::name('xt_caijin')->where('id',1)->find();
            if($t['open'] == 1) {
                $je = $t['je'];
                $dml = $t['cj_dml'];
            } else {
                $je = 0;
                $dml = 0;
            }
            //将用户信息插入表
            $reg_pass = md5($reg_pass);
            $ntime = time();
            $login_key = suiji_zifu(15);

            $user_model->setNewUser($arr['id'],$dml,$reg_user,$reg_pass,$arr['username'],$je,$ntime,$this->login_ip,$position,1,'',0,2,$login_key);
            $data['mobile']=$phone;
            $data['zcjje'] = $je;
            $data['reg_je'] = $je;
            /*if($arr['recommend'][1]>0){
                $data['dl']=1;
                $data['dl_time'] = time();
                $data['tjm']=$this->code();
                $data['fandian']=$arr['recommend'][1];
            }*/
            Db::name('username')->where('username',$reg_user)->update($data);
            $us = Db::name('username')->where('username',$reg_user)->value('id');
            /*$id = $us;
            if(strlen($us)==1){$id='00000'.$us;}
            if(strlen($us)==2){$id='0000'.$us;}
            if(strlen($us)==3){$id='000'.$us;}
            if(strlen($us)==4){$id='00'.$us;}
            if(strlen($us)==5){$id='0'.$us;}
            $dt = array('tjm'=>$id);
            Db::name('username')->where('id',$us)->update($dt);*/
            if($je>0){
                $this->state->UserFaSong($reg_user, "您注册账号赠送：".$je."元.已到账，请注意查收！");
                $data = array(
                    'username'=>$reg_user,
                    'user_class'=>1,
                    'cjje'=>$je,
                    'fstime'=>time(),
                    'beizhu' => '系统赠送，手机H5用户注册，赠送彩金',
                    'czadmin' => '系统赠送',
                    'cjhje'=>$je,
                );
                Db::name('caijin_list')->insert($data);
            }

            Db::name('username')->where('username',$reg_user)->setInc('login_num');
            echo 'ok';
        } else {
            echo 1;exit;
        }

    }
}
